package com.example.jiagoujiexiang.Controller;

import com.example.jiagoujiexiang.Exption.MD5Util;
import com.example.jiagoujiexiang.Exption.ServiceException;
import com.example.jiagoujiexiang.Service.adminService;
import com.example.jiagoujiexiang.Utils.Constant;
import com.example.jiagoujiexiang.entity.Pet;
import com.example.jiagoujiexiang.entity.User;
import com.example.jiagoujiexiang.entity.subscribe;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import com.example.jiagoujiexiang.Service.petService;
import com.example.jiagoujiexiang.Service.userService;
import com.example.jiagoujiexiang.Service.subService;
import com.example.jiagoujiexiang.Service.getLoveService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
public class userController {
    @Autowired
    userService userService ;
    @Autowired
    petService petService ;
    @Autowired
    subService subService ;
    @Autowired
    adminService adminService;
    @Autowired
    getLoveService getLoveService;

    @GetMapping("/login")
    public ModelAndView login() {
        return new ModelAndView("login");
    }
    @GetMapping("/zhuce")
    public ModelAndView zhuce1() {
        return new ModelAndView("zhuce");
    }


    @PostMapping("/zhuce-complete")
    public String zhuce(User user, Model model) {
        User userVerify = userService.getUserByNum(user);
        if (userVerify != null) {
            model.addAttribute("loginSuccess", true);
            model.addAttribute("message", "注册成功！");
            model.addAttribute("index_petsList", petService.getpetList());
            return "index";
        } else {
            model.addAttribute("loginSuccess", false);
            model.addAttribute("message", "注册失败，昵称已存在或者输入违规！！");
            return "zhuce";
        }

    }
    @GetMapping("/success")
    public String success() {
        return "success";
    }
    @PostMapping("/loginin")
    public String loginin(User user, HttpSession httpSession, Model model) {
        User user1 = userService.insertUser(user);
        try {
            if (user1 != null) {
                httpSession.setAttribute(Constant.LOGIN_USER, user1.getUsername());
                model.addAttribute("loginSuccess", true);
                model.addAttribute("message", "登录成功！");
                model.addAttribute("username", user1.getUsername());
                model.addAttribute("index_petsList", petService.getpetList());
                if ("admin".equals(user1.getUsername())) {
                    return "redirect:/admin"; // 如果是管理员，重定向到 /admin
                } else {
                    return "index"; // 否则重定向到首页
                }
            } else {
                return "zhuce";
            }
        } catch (Exception e) {
            model.addAttribute("loginSuccess", false);
            model.addAttribute("message", e.getMessage());
            return "error";
        }
    }

    @GetMapping("/quituser")
    public String quituser(HttpSession session, Model model) {
        // 清除会话中的 username
        session.removeAttribute("username");
        return "lose";
    }

    @GetMapping("/userdetails1")
    public String userdetails1(HttpSession session, Model model) {
        addUsernameToModel(session, model); // 添加 username 到模型中
        return "userDetails";
    }

    @PostMapping("/userdetails")
    public String userdetails(HttpSession httpSession, User user,Model model) {
        User user1 = (User) httpSession.getAttribute(Constant.LOGIN_USER);
        String MD5password = MD5Util.md5(user.getPassword());
        user.setPasswordSecret(MD5password);
        int bool = userService.updateuserde(user, user1);
        if (bool == 1) {
            model.addAttribute("loginSuccess", false);
            model.addAttribute("message", "修改成功！");
            model.addAttribute("index_petsList", petService.getpetList());
            addUsernameToModel(httpSession, model);
            return "redirect:/index";
        } else {
            return "userDetails";
        }
    }

    @GetMapping("/myLove")
    public String myLove(HttpSession httpSession, @RequestParam(name = "lovePage", defaultValue = "1") int lovePage,Model model) {

        User user1 = userService.getUserByName((String) httpSession.getAttribute(Constant.LOGIN_USER));
        model.addAttribute("loveDogs", petService.getLovepetdog1(user1.getId()));
        model.addAttribute("loveCats", petService.getLovepetcat1(user1.getId()));
        int count = petService.getLovepetdog1(user1.getId()).size() + petService.getLovepetcat1(user1.getId()).size();
        model.addAttribute("countPets", count);
        model.addAttribute("countPetpage", lovePage);
        addUsernameToModel(httpSession, model);
        return "myLove";
    }
    @GetMapping("/addmylove")
    public String addMyLove(HttpSession httpSession,
                            @RequestParam(name = "petdetail") int petdetail,
                            Model model,
                            RedirectAttributes redirectAttributes) {
        try {
            // 获取当前登录用户
            String username = (String) httpSession.getAttribute(Constant.LOGIN_USER);
            if (username == null) {
                redirectAttributes.addFlashAttribute("loginSuccess", false);
                redirectAttributes.addFlashAttribute("message", "请先登录");
                return "redirect:/login"; // 重定向到登录页面
            }

            User user1 = userService.getUserByName((String) httpSession.getAttribute(Constant.LOGIN_USER));
            getLoveService.love(user1.getId(),petdetail);

            // 添加成功消息
            redirectAttributes.addFlashAttribute("loginSuccess", true);
            redirectAttributes.addFlashAttribute("message", "已成功添加到我的喜欢");
        } catch (Exception e) {
            // 添加错误消息
            redirectAttributes.addFlashAttribute("loginSuccess", false);
            redirectAttributes.addFlashAttribute("message", e.getMessage());
        }
        Pet pet=null;
        if (petService.getdogsde(petdetail) == null) pet=petService.getcatsde(petdetail);
        else pet=petService.getdogsde(petdetail);
        if(pet.getName().indexOf("犬") != -1){
            // 重定向回原页面
            return "redirect:/dogsDetails?petdetail=" + petdetail;
        }else {
            // 重定向回原页面
            return "redirect:/catsDetails?petdetail=" + petdetail;
        }

    }

    @GetMapping("/userSubscribe")
    public String userSubscribe(HttpSession httpSession, Model model) {
        User user1 = userService.getUserByName((String) httpSession.getAttribute(Constant.LOGIN_USER));
        model.addAttribute("subDogs", petService.getsubpetdog1(user1.getId()));
        model.addAttribute("subCats", petService.getsubpetcat1(user1.getId()));
        int count = petService.getsubpetdog1(user1.getId()).size() + petService.getsubpetcat1(user1.getId()).size();
        model.addAttribute("countPets", count);
        addUsernameToModel(httpSession, model);
        return "userSubscribe";
    }
    @PostMapping("/addsub")
    public String addsub(Model model, HttpSession httpSession,  @RequestParam("pet_id") @Param("pet_id") int pet_id,
                         @RequestParam("appointmentTime") @Param("appointmentTime") Date dataTime){
        User user1 = userService.getUserByName((String) httpSession.getAttribute(Constant.LOGIN_USER));
        System.out.println("appointmentTime: " + dataTime);
        subscribe sub=new subscribe();
        sub.setTimestamp(dataTime);
        sub.setUser_id(user1.getId());
        sub.setPet_id(pet_id);
        int a=subService.addSubService(sub);
        Pet pet=null;
        if (petService.getdogsde(pet_id) == null) pet=petService.getcatsde(pet_id);
        else pet=petService.getdogsde(pet_id);
        if(a==1){
            if(pet.getName().indexOf("犬") != -1){
                petService.setsubDog(pet_id);
            }else {
                petService.setsubcat(pet_id);
            }
            addUsernameToModel(httpSession, model);
            return "redirect:/userSubscribe";
        }else{
            throw new ServiceException("预约失败");
        }
    }
    private void addUsernameToModel(HttpSession session, Model model) {
        User user = userService.getUserByName((String) session.getAttribute(Constant.LOGIN_USER));
        if (user != null) {
            model.addAttribute("username", user.getUsername());
        }
    }

    @GetMapping("/upUser")
    public String upUser(HttpSession session, Model model) {
        User user = userService.getUserByName((String) session.getAttribute(Constant.LOGIN_USER));
        model.addAttribute("user", user);

        return "userDetails";
    }
    @PostMapping("/upUser")
    public String upUserdata(@ModelAttribute User user, RedirectAttributes redirectAttributes) {
        String MD5password = MD5Util.md5(user.getPassword());
        user.setPasswordSecret(MD5password);
        userService.updateUseradmin(user);
        redirectAttributes.addFlashAttribute("message", "修改成功，请重新登录");
        return "redirect:/login";
    }
}
